package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import cn.com.kh.signUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.parser.Feature
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: 网聊访客登录* @author: LiJuntao* @date 2021-07-13 23:58:55
 *
 */

public class apiSendSMS implements ServiceBackInvoke {

    private static final Log log = LogFactory.getLog(apiSendSMS.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 调用IP过滤
        if (KHDBConfig.getParamConfig(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("[API被非法IP调用]-Request Not Allow!");
            return "Request Not Allow!";
        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject result = new JSONObject();

        // 接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }
        log.info("[调用请求信息]:" + callJson);

        try {
            JSONObject callObj = JSONObject.parseObject(callJson, Feature.OrderedField);

            JSONObject signJson = signUtil.CheckSign(callObj);
            log.info("[签名验证结果]:");
            log.info(signJson);

            // 解析
            JSONArray dataList = callObj.getJSONArray("data");
            JSONArray dataRes = new JSONArray();
            int dataListSize = dataList.size();
            for (int i = 0; i < dataListSize; i++) {
                JSONObject dataArr = new JSONObject();
                try {
                    String mobile = dataList.getJSONObject(i).containsKey("mobile") ? dataList.getJSONObject(i).getString("mobile") : "";
                    String content = dataList.getJSONObject(i).containsKey("content") ? dataList.getJSONObject(i).getString("content") : "";
                    String smsid = dataList.getJSONObject(i).containsKey("smsid") ? dataList.getJSONObject(i).getString("smsid") : "";
                    String userno = dataList.getJSONObject(i).containsKey("userno") ? dataList.getJSONObject(i).getString("userno") : "";
                    String sms_type = dataList.getJSONObject(i).containsKey("sms_type") ? dataList.getJSONObject(i).getString("sms_type") : "";

                    dataArr.put("smsid", smsid);
                    dataArr.put("mobile", mobile);
                    dataArr.put("content", content);

                    // 非空检查
                    String checkNull = KHUtil.isNullMSG("smsid", smsid) + KHUtil.isNullMSG("mobile", mobile) + KHUtil.isNullMSG("content", content);
                    if (!KHUtil.isNull(checkNull)) {
                        dataArr.put("code", -1);
                        dataArr.put("msg", checkNull);
                        dataRes.push(dataArr);

                    } else {

                        // 检查短信是否已经发送
                        String selectSQL = "Select Documentout_Guid From Documentout Where Sms_Guid = ?"
                        List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, smsid);
                        if (selectExits.size() > 0) {
                            dataArr.put("code", -2);
                            dataArr.put("msg", "当前smsid重复发送");
                            dataRes.push(dataArr);
                        } else {

                            String insertSQL = '''Insert Into Documentout
                                          (Documentout_Guid,
                                           Doctype,
                                           Status,
                                           Trialcount,
                                           Trialcountlimit,
                                           Documentpath,
                                           Handleby_Id,
                                           Handlegroup_Id,
                                           Createdby,
                                           Createddate,
                                           Expectedstartdate,
                                           Documentto,
                                           Stringfield1,
                                           Sub_Doctype,
                                           Sms_Guid,
                                           Ucisid)
                                          Select Newid(),
                                                 3 AS Doctype,
                                                 3 AS Status,
                                                 0 AS Trialcount,
                                                 5 AS Trialcountlimit,
                                                 ? AS Documentpath,
                                                 'SELITE' AS Handleby_Id,
                                                 'SYSTEM' AS Handlegroup_Id,
                                                 'SELITE' AS Createdby,
                                                 Getdate() AS Createddate,
                                                 Getdate() AS Expectedstartdate,
                                                 ? AS Documentto,
                                                 'CRM外部短信接口' AS Stringfield1,
                                                 ? As Sub_Doctype,
                                                 ? As Sms_Guid,
                                                 ? As Ucisid''';
                            int updateNum = jt.update(insertSQL, content, mobile, sms_type, smsid, userno);
                            if (updateNum > 0) {
                                dataArr.put("code", 1);
                                dataArr.put("msg", "发送成功");
                                dataRes.push(dataArr);

                            } else {
                                dataArr.put("code", 2);
                                dataArr.put("msg", "发送成功");
                                dataRes.push(dataArr);

                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("接口处理异常" + e.getMessage());
                    dataArr.put("code", -1);
                    dataArr.put("msg", e.getMessage());
                    dataRes.push(dataArr);
                }
            }
            result.put("code", 1);
            result.put("message", "发送完成,总条数:" + dataListSize);
            result.put("data", dataRes);
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            result.put("code", 0);
            result.put("message", "发送失败,接口处理异常:" + e.getMessage());
            result.put("data", []);

        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "[SMS]CRM外部短信接口", "apiSendSMS", callJson, result.toString(), (System.currentTimeMillis() - startTime).toString(), "/");
        }

        log.debug("SMS数据接入处理完成返回结果:" + result.toString());

        return result.toString();
    }

}